<script>
	import store from './store'
    import { my_load } from '@/api/user.js'
    import { getWechat } from "@/api/public.js"
	import Auth from './libs/wechat.js'
	import {editVideoTime} from "@/api/useryk.js"
	export default {
		globalData:{
			systemName:'掌信微直播',
			barHeight:0,
			isIframe:false,
			jx_id:'',//经销商id
			qun_id:'',//群主id
			spread:0,
            platform:'',
            // 微信appid
            wx_appid: "",
		},
		onLaunch: function(option) {
            // 判断是否是微信客户端
            const isWechat = () => {
            	// true是微信客户端，false不是微信客户端
            	const ua = window.navigator.userAgent.toLowerCase()
            	return ua.match(/micromessenger/i) == 'micromessenger'
            }
            
            // 判断是否是微信浏览器，改项目目前只允许运行到微信
            if(!isWechat()){
               uni.reLaunch({
                   url: '/pages/evn'
               })
               return
            } 
            
			// console.log('App Launch')
			let that=this
			uni.getSystemInfo({
				success: function(res) {
					// console.log('res',res)
					// 状态栏是动态的可以拿到 标题栏是固定写死的是44px
					// #ifdef MP || APP-PLUS
					that.globalData.barHeight = statusBarHeight
					// #endif
					// #ifdef H5 
					that.globalData.barHeight = 44;
					// #endif
					that.globalData.platform = res.platform
					// console.log('barHeight',that.globalData.barHeight)
					store.commit('GET_GLOBAL', JSON.parse(JSON.stringify(that.globalData)));
				}
			});
			// #ifdef H5
			if (option.query.hasOwnProperty('type') && option.query.type == "iframeVisualizing") {
				this.globalData.isIframe = true;
			} else {
				this.globalData.isIframe = false;
			}            
			let snsapiBase = 'snsapi_base';
			let urlData = location.pathname + location.search;
			// console.log('location.pathname', option.path)
			// console.log('group', option.path.indexOf('group') === -1 )
			let isGroup = option.path.indexOf('group') === -1 ? false : true
			// console.log('isGroup', isGroup )
			// console.log('that.$store.getters.isLogin',that.$store.getters.isLogin)
			// if (!that.$store.getters.isLogin && Auth.isWeixin()) {
			// if (!that.$store.getters.isLogin) {
				
			// 	console.log('option.query',option.query)
			// 	that.globalData.jx_id = option.query.jx_id ? option.query.jx_id : ''				
			// 	store.commit('GET_GLOBAL', JSON.parse(JSON.stringify(that.globalData)));
				
				const {
					code,
					state,
					jx_id,
					qun_id,
					id
				} = option.query;
				// console.log('参数', option.query)
				if(isGroup){//群主端
					// console.log('11111111')
					// if (!that.$store.getters.isLogin && Auth.isWeixin()) {
						if (code && code != uni.getStorageSync('snsapiCode') && location.pathname.indexOf('/pages/group/login/index') === -1) {
						// if (code  && location.pathname.indexOf('/pages/group/login/index') === -1) {
							// 存储静默授权code
							uni.setStorageSync('snsapiCode', code);
							that.globalData.jx_id = jx_id || that.globalData.jx_id 
							that.$store.commit('GET_GLOBAL', JSON.parse(JSON.stringify(that.globalData)));
							Auth.auth(code, jx_id || that.globalData.jx_id)
								.then(res => {
									uni.setStorageSync('snRouter', decodeURIComponent(decodeURIComponent(option.query.back_url)));
									that.$store.commit('LOGIN', {
										token: res.token
									});
									that.$store.commit("SETUID", res.data.id);
									that.$store.commit('UPDATE_USERINFO',res.data)
									if (res.yi_tow === 'register' || (res.yi_tow === 'login' && (res.data.tel === null || res.data.tel === ''))) {
										location.replace('/pages/group/user/user-tel');
									}else if (res.yi_tow === 'login') {
										location.replace(decodeURIComponent(decodeURIComponent(option.query.back_url)));
									}
								})
								.catch(error => {
                                    alert(error)
									if (location.pathname.indexOf('/pages/group/login/index') === -1) {
										location.replace('/pages/group/login/index')
									}
								});
						} else if(!that.$store.getters.isLogin){
          
							if (location.pathname.indexOf('/pages/group/login/index') === -1) {
								location.replace('/pages/group/login/index')
							} 
						}
					// }else{
					// 	if (option.query.back_url) {
					// 		location.replace(uni.getStorageSync('snRouter'));
					// 	}else {
     //                        location.replace(`/pages/group/index/index`)
     //                    }
					// }
                    
                    // 如果登录了获取群主信息
                    if(that.$store.getters.isLogin){
                        my_load().then(res=>{
                            
                            // 群主信息审核没通过，直接跳转到结束页面
                            if(res.data.is_sh == 2){
                                uni.redirectTo({
                                    url: '/pages/group/index/tips?type=1'
                                })
                                
                            }else if(res.data.is_zt == 2){
                                uni.redirectTo({
                                    url: '/pages/group/index/tips?type=2'
                                })
                            }
                            
                        	that.$store.commit("SETUID", res.data.id);
                        	that.$store.commit('UPDATE_USERINFO',res.data)
                        }).catch(err => {})
                    }
				}else{//会员端
					// if(!that.$store.getters.isUserLogin){
                        // console.log('sssssssss')
                        
						// if (code && code != uni.getStorageSync('snsapiUserCode') && location.pathname.indexOf('/pages/login/index') === 0) {
						if (code  && location.pathname.indexOf('/pages/login/index') === 0) {
							uni.setStorageSync('snsapiUserCode', code);
							let vid = uni.getStorageSync('vid')
							if(id && id !== vid && id !== undefined){
								vid = id
								uni.setStorageSync('vid', id);
							}
							that.globalData.qun_id = that.globalData.qun_id ? that.globalData.qun_id : ''
                            
							that.$store.commit('GET_GLOBAL', JSON.parse(JSON.stringify(that.globalData)));
							console.log('111111', qun_id || that.globalData.qun_id)
                       
							Auth.userAuth(code, qun_id || that.globalData.qun_id )
								.then(res => {
									uni.setStorageSync('snUserRouter', decodeURIComponent(decodeURIComponent(option.query.back_url)));
										// console.log('auth',res)
										that.$store.commit('LOGINUSER', {
											token: res.token
										});
										that.$store.commit("SETUIDUSER", res.data.id);
										that.$store.commit('UPDATE_USERINFO_USER',res.data)
										uni.navigateTo({
											animationType:that.$animationType.type,
											animationDuration:that.$animationType.duration,
											url:`/pages/index/index?id=${vid}`
										})
								})
								.catch(error => {
                                    alert(error)
									if (location.pathname.indexOf('/pages/login/index') === -1) {
										// location.replace(`/pages/user_login/index?qun_id=${that.globalData.qun_id}`)
										location.replace(`/pages/login/index`)
									}
								});
                       
						}else if(!that.$store.getters.isUserLogin){
							if (location.pathname.indexOf('/pages/login/index') === -1) {
								// console.log('2222')
								// location.replace(`/pages/user_login/index?qun_id=${that.globalData.qun_id}`)
								location.replace(`/pages/login/index?id=${ id }&qun_id=${qun_id}`)
							} 
						}						
					// }else{
					// 	if (option.query.back_url) {
					// 		location.replace(uni.getStorageSync('snUserRouter'));
					// 	}else {
     //                        location.replace(`/pages/index/index?id=` + id)
     //                    }
					// }
                    

				}				
			// #endif
			store.commit('GET_GLOBAL', JSON.parse(JSON.stringify(that.globalData)));
            
            /**
             * 获取配置数据
             */
            getWechat().then(res => {
                getApp().globalData.wx_appid = res.data.wx_appid
            }).catch(err => {
                
            })
		},
		onShow: function() {
			uni.setStorageSync('url',window.location.href) //在App.vue中获取并缓存
			// #ifdef H5
			// 	uni.getSystemInfo({
			// 		success(e) {
			// 			/* 窗口宽度大于420px且不在PC页面且不在移动设备时跳转至 PC.html 页面 */
			// 			if (e.windowWidth > 420 && !window.top.isPC && !/iOS|Android/i.test(e.system)) {
			// 				// window.location.pathname = 'https://java.crmeb.net/';
			// 				/* 若你的项目未设置根目录（默认为 / 时），则使用下方代码 */
			// 				window.location.pathname = '/static/html/pc.html';
			// 			}
			// 		}
			// 	})
			// #endif
			
		},
		async mounted() {
			
			if (this.$store.getters.isLogin && !this.$Cache.get('USER_INFO')) await this.$store.dispatch('USERINFO');
		},
		onHide: function() {
			console.log('App Hide')
			// this.editVideoTime()
		},
		onUnload:function() {
			// this.editVideoTime()
		},
		methods:{
			//上传播放时长
			// editVideoTime(){
			// 	let vid = uni.getStorageSync('vid')
			// 	let videoDuration = uni.getStorageSync('videoDuration')
			// 	if(videoDuration*1 > 0 && vid > 0 ){
			// 		let param = {
			// 			id:vid,
			// 			duration:videoDuration*1
			// 		}
			// 		editVideoTime(param).then(res=>{
			// 			// this.$util.Tips({
			// 			// 	title:'上传成功'
			// 			// })
			// 		})
			// 	}
			// }
		}
	}
</script>

<style lang="scss">
	/*每个页面公共css */
	@import url("static/css/font.css");
	@import url("static/css/basc.css");
	@import url("static/css/style.scss");
	@import url("static/font/iconfont.css");
    
    @import "uview-ui/index.scss";
    
    
</style>
